<template>
  <div class="total-overview page">
    <div class="header">
      <h2>总览</h2>
      <div class="controls">
        <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" size="small" />
        <el-select v-model="dept" placeholder="选择科室" size="small" style="min-width:160px">
          <el-option v-for="d in depts" :key="d" :label="d" :value="d" />
        </el-select>
        <el-button type="primary" @click="refresh" size="small">刷新</el-button>
        <el-button @click="exportOverview" size="small">导出</el-button>
      </div>
    </div>

    <el-row :gutter="16" class="kpi-row">
      <el-col :xs="24" :sm="12" :md="8" :lg="4" v-for="card in kpis" :key="card.title">
        <el-card class="kpi-card" shadow="always">
          <div class="kpi-title">{{ card.title }}</div>
          <div class="kpi-value">{{ card.value }}</div>
          <div class="kpi-sub" v-if="card.sub">{{ card.sub }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="charts-row">
      <el-col :xs="24" :md="14">
        <el-card shadow="never" class="chart-card">
          <div class="card-header">
            <div class="card-title">消耗趋势</div>
            <el-radio-group v-model="trendMode" size="small">
              <el-radio-button label="total">总量</el-radio-button>
              <el-radio-button label="byDept">按科室</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="trendChart" class="chart" />
        </el-card>

        <el-card shadow="never" class="table-card" style="margin-top:12px">
          <div class="card-title">低库存药品</div>
          <el-table :data="lowStocks" style="width:100%" size="small" stripe>
            <el-table-column prop="drugName" label="药品" />
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="threshold" label="警戒线" width="100" />
            <el-table-column label="操作" width="140">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="goReplenish(row)">补货</el-button>
                <el-button type="text" size="small" @click="viewDrug(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="10">
        <el-card shadow="never" class="chart-card">
          <div class="card-header">
            <div class="card-title">药品消耗 Top10</div>
            <el-select v-model="topN" size="small" style="min-width:80px">
              <el-option label="5" :value="5" />
              <el-option label="10" :value="10" />
              <el-option label="20" :value="20" />
            </el-select>
          </div>
          <div ref="barChart" class="chart small" />
        </el-card>

        <el-card shadow="never" class="chart-card" style="margin-top:12px">
          <div class="card-header">
            <div class="card-title">医生处方排名</div>
            <div class="muted">按处方数排序</div>
          </div>
          <div ref="doctorChart" class="chart small" />
        </el-card>
      </el-col>
    </el-row>

    <div class="quick-links">
      <el-button type="primary" plain @click="goTo('consumptionAnalysis')">消耗量分析</el-button>
      <el-button plain @click="goTo('specialLibrary')">专库实时监控</el-button>
      <el-button plain @click="goTo('patientMedRecords')">患者用药记录</el-button>
      <el-button plain @click="goTo('prescriptionReview')">处方审核</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';

const router = useRouter();
const range = ref([]);
const dept = ref('全部科室');
const depts = ['全部科室', '门诊', '住院', '急诊', '精神科'];
const trendMode = ref('total');
const topN = ref(10);

// KPI mock data
const kpis = ref([
  { title: '活跃患者', value: 482, sub: '较上周 +4.2%' },
  { title: '总消耗量（单位）', value: 1286, sub: '近7天' },
  { title: '待审核处方', value: 7, sub: '需要处理' },
  { title: '低库存药品', value: 3, sub: '请尽快补货' },
  { title: '设备离线', value: 1, sub: '检查设备连通' },
  { title: '随访完成率', value: '72%', sub: '较上月 +6%' }
]);

// Mock datasets
const mockTrend = (() => {
  const days = 14; const arr = [];
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(); d.setDate(d.getDate() - i);
    const label = `${d.getMonth() + 1}/${d.getDate()}`;
    arr.push({ date: label, total: Math.round(600 + Math.random() * 400), 门诊: Math.round(200 + Math.random() * 150), 住院: Math.round(150 + Math.random() * 120), 急诊: Math.round(100 + Math.random() * 80) });
  }
  return arr;
})();

const mockTopDrugs = (() => {
  const names = ['劳拉西泮', '奥氮平', '氟哌啶醇', '舍曲林', '利培酮', '氯丙嗪', '米氮平', '艾司唑仑', '阿普唑仑', '曲唑酮', '其他'];
  return names.map((n, i) => ({ drugName: n, consumed: Math.round(50 + Math.random() * 400 - i * 10) })).sort((a, b) => b.consumed - a.consumed);
})();

const mockDoctors = (() => {
  const docs = [];
  for (let i = 1; i <= 8; i++) docs.push({ name: `Dr. 张${i}`, prescriptions: Math.round(20 + Math.random() * 120) });
  docs.sort((a, b) => b.prescriptions - a.prescriptions);
  return docs;
})();

const lowStocks = ref([
  { drugName: '氟哌啶醇注射液', stock: 6, threshold: 10 },
  { drugName: '劳拉西泮片', stock: 3, threshold: 20 },
  { drugName: '奥氮平片', stock: 8, threshold: 15 }
]);

// chart refs
const trendChart = ref(null);
const barChart = ref(null);
const doctorChart = ref(null);
let trendInstance, barInstance, doctorInstance;

function initTrend() {
  if (!trendChart.value) return;
  trendInstance = echarts.init(trendChart.value);
  const dates = mockTrend.map(x => x.date);
  const series = [];
  if (trendMode.value === 'total') {
    series.push({ name: '消耗总量', type: 'line', data: mockTrend.map(x => x.total), smooth: true, areaStyle: {} });
  } else {
    ['门诊', '住院', '急诊'].forEach(k => series.push({ name: k, type: 'line', data: mockTrend.map(x => x[k]), smooth: true }));
  }
  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: series.map(s => s.name) },
    xAxis: { type: 'category', data: dates, boundaryGap: false },
    yAxis: { type: 'value' },
    series
  };
  trendInstance.setOption(option);
}

function initBar() {
  if (!barChart.value) return;
  barInstance = echarts.init(barChart.value);
  const top = mockTopDrugs.slice(0, topN.value);
  const option = {
    tooltip: {},
    xAxis: { type: 'value' },
    yAxis: { type: 'category', data: top.map(d => d.drugName).reverse(), axisLabel: { formatter: v => v } },
    series: [{ type: 'bar', data: top.map(d => d.consumed).reverse(), itemStyle: { color: '#409EFF' } }]
  };
  barInstance.setOption(option);
}

function initDoctor() {
  if (!doctorChart.value) return;
  doctorInstance = echarts.init(doctorChart.value);
  const top = mockDoctors.slice(0, 6);
  const option = {
    tooltip: {},
    xAxis: { type: 'value' },
    yAxis: { type: 'category', data: top.map(d => d.name).reverse() },
    series: [{ type: 'bar', data: top.map(d => d.prescriptions).reverse(), itemStyle: { color: '#67C23A' } }]
  };
  doctorInstance.setOption(option);
}

onMounted(() => {
  nextTick(() => {
    initTrend(); initBar(); initDoctor();
    window.addEventListener('resize', resizeCharts);
  });
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  try { trendInstance && trendInstance.dispose(); barInstance && barInstance.dispose(); doctorInstance && doctorInstance.dispose(); } catch (e) {}
});

watch([trendMode], () => { initTrend(); });
watch([topN], () => { initBar(); });

function resizeCharts() { try { trendInstance && trendInstance.resize(); barInstance && barInstance.resize(); doctorInstance && doctorInstance.resize(); } catch (e) {} }

function refresh() { // in real app would fetch data
  // animate a small change in mock data
  mockTopDrugs.forEach(m => { m.consumed = Math.max(3, Math.round(m.consumed * (0.9 + Math.random() * 0.3))); });
  mockDoctors.forEach(d => { d.prescriptions = Math.max(1, Math.round(d.prescriptions * (0.9 + Math.random() * 0.3))); });
  initTrend(); initBar(); initDoctor();
}

function exportOverview() {
  const rows = [['指标','数值']].concat(kpis.value.map(k => [k.title, k.value]));
  const txt = rows.map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([txt], { type: 'text/csv' });
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'overview.csv'; a.click(); URL.revokeObjectURL(url);
}

function goReplenish(row) { alert(`跳转到补货：${row.drugName}`); }
function viewDrug(row) { alert(`查看药品：${row.drugName}`); }
function goTo(url) { // map to route names used in project
  const map = { consumptionAnalysis: '/consumptionAnalysis', specialLibrary: '/specialLibrary', patientMedRecords: '/patientMedRecords', prescriptionReview: '/prescriptionReview' };
  router.push(map[url] || '/');
}

</script>

<style scoped>
.page{padding:12px;font-family: Arial, "Microsoft YaHei", sans-serif}
.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}
.header h2{margin:0}
.controls{display:flex;gap:8px;align-items:center}
.kpi-row{margin-bottom:12px}
.kpi-card{padding:12px;text-align:center}
.kpi-title{color:#666;font-size:12px}
.kpi-value{font-size:20px;font-weight:600;margin-top:6px}
.kpi-sub{color:#999;font-size:12px;margin-top:6px}
.charts-row{margin-top:6px}
.chart-card{height:360px;display:flex;flex-direction:column}
.card-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}
.card-title{font-weight:600}
.chart{height:260px}
.chart.small{height:180px}
.table-card{padding:12px}
.muted{color:#888;font-size:12px}
.quick-links{margin-top:12px;display:flex;gap:8px}
</style>
